'use client'

import { useEffect, useState } from 'react'
import { VmsTopic, VmsCopy } from '@/types/Model'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { useParams, useRouter } from 'next/navigation'
import moment from 'moment'
import { toast } from '@/hooks/use-toast'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"

import { Label } from "@/components/ui/label"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"

export default function TopicDetailPage() {
  const { id } = useParams()
  const router = useRouter()
  const [topic, setTopic] = useState<VmsTopic | null>(null)
  const [copies, setCopies] = useState<VmsCopy[]>([])
  const [loading, setLoading] = useState(true)
  const [dialogOpen, setDialogOpen] = useState(false)
  const [currentCopy, setCurrentCopy] = useState<VmsCopy>({
    id: '',
    title: '',
    intro: '',
    topic_id: id as string,
    status: '文案编辑中',
    script_num: 0,
    finished_script_num: 0,
    cjsj: new Date()
  })
  const [isEditing, setIsEditing] = useState(false)

  const fetchTopicAndCopies = async () => {
    try {
      const token = localStorage.getItem('token')
      
      // Fetch topic details
      const topicResponse = await fetch(`/api/topic/${id}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!topicResponse.ok) {
        throw new Error('Failed to fetch topic details')
      }
      const topicData = await topicResponse.json()
      setTopic(topicData)

      // Fetch copies
      const copiesResponse = await fetch(`/api/copy?topic_id=${id}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!copiesResponse.ok) {
        throw new Error('Failed to fetch copies')
      }
      const copiesData = await copiesResponse.json()
      setCopies(copiesData)

      toast({
        title: '数据获取成功',
        description: '话题详情和复制列表已加载',
      })
    } catch (error) {
      console.error('Error fetching data:', error)
      toast({
        title: '数据获取失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    } finally {
      setLoading(false)
    }
  }

  const handleSaveCopy = async () => {
    try {
      const token = localStorage.getItem('token')
      const method = isEditing ? 'PUT' : 'POST'
      const url = isEditing ? `/api/copy` : '/api/copy'

      const response = await fetch(url, {
        method,
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(currentCopy),
      })

      if (!response.ok) {
        throw new Error(isEditing ? '更新文案失败' : '创建文案失败')
      }

      toast({
        title: isEditing ? '更新成功' : '创建成功',
        description: isEditing ? '文案已更新' : '新文案已创建',
      })
      setDialogOpen(false)
      resetCopyForm()
      fetchTopicAndCopies()
    } catch (error) {
      toast({
        title: isEditing ? '更新失败' : '创建失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  const resetCopyForm = () => {
    setCurrentCopy({
      id: '',
      title: '',
      intro: '',
      topic_id: id as string,
      status: '文案编辑中',
      script_num: 0,
      finished_script_num: 0,
      cjsj: new Date()
    })
    setIsEditing(false)
  }

  const handleDeleteCopy = async (copy_id: string) => {
    try {
      const confirmDelete = window.confirm('确定要删除这个文案吗？此操作不可撤销。')
      if (!confirmDelete) return

      const token = localStorage.getItem('token')
      const response = await fetch(`/api/copy/${copy_id}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (!response.ok) {
        throw new Error('删除文案失败')
      }

      toast({
        title: '删除成功',
        description: '文案已删除',
      })
      fetchTopicAndCopies()
    } catch (error) {
      toast({
        title: '删除失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  useEffect(() => {
    if (id) {
      fetchTopicAndCopies()
    }
  }, [id])

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
      </div>
    )
  }

  if (!topic) {
    return <div>未找到话题</div>
  }

  return (
    <div className="container mx-auto p-4">
      <div className="mb-8">
        <div className="flex items-center gap-4 mb-2">
          <h1 className="text-2xl font-bold">{topic.name}</h1>
          <span className="text-sm text-muted-foreground px-2 py-1 bg-gray-100 rounded">
            {topic.status}
          </span>
        </div>
        <h2 className="text-lg text-muted-foreground mb-4">{topic.target}</h2>
        <p className="text-sm text-gray-500">
          创建时间: {moment(topic.cjsj).format('YYYY-MM-DD HH:mm')}
        </p>
      </div>

      <div className="flex justify-between items-center mb-4">
        <h2 className="text-xl font-bold">文案列表</h2>
        <Dialog open={dialogOpen} onOpenChange={(open) => {
          if (!open) resetCopyForm()
          setDialogOpen(open)
        }}>
          <DialogTrigger asChild>
            <Button>新增文案</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{isEditing ? '编辑文案' : '创建新文案'}</DialogTitle>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="title" className="text-right">
                  标题
                </Label>
                <Input
                  id="title"
                  value={currentCopy.title}
                  onChange={(e) => setCurrentCopy({...currentCopy, title: e.target.value})}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="intro" className="text-right">
                  简介
                </Label>
                <Textarea
                  id="intro"
                  value={currentCopy.intro}
                  onChange={(e) => setCurrentCopy({...currentCopy, intro: e.target.value})}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="status" className="text-right">
                  状态
                </Label>
                <Select 
                  value={currentCopy.status} 
                  onValueChange={(value) => setCurrentCopy({...currentCopy, status: value})}
                >
                  <SelectTrigger className="col-span-3">
                    <SelectValue placeholder="选择状态" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="文案编辑中">文案编辑中</SelectItem>
                    <SelectItem value="脚本制作中">脚本制作中</SelectItem>
                    <SelectItem value="拍摄中">拍摄中</SelectItem>
                    <SelectItem value="已完成">已完成</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <Button onClick={handleSaveCopy}>{isEditing ? '保存' : '创建'}</Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <Table>
        <TableHeader>
          <TableRow>
            <TableHead className="w-2/12">标题</TableHead>
            <TableHead className="w-3/12">简介</TableHead>
            <TableHead className="w-1/12">状态</TableHead>
            <TableHead className="w-1/12">文案进度</TableHead>
            <TableHead className="w-2/12">创建时间</TableHead>
            <TableHead className="w-2/12">操作</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {copies.map(copy => (
            <TableRow key={copy.id}>
              <TableCell className="w-2/12">
                <Button
                  variant="link"
                  className="p-0 text-left"
                  onClick={() => window.open(`/copy/${copy.id}`,'_blank')}
                >
                  {copy.title}
                </Button>
              </TableCell>
              <TableCell className="w-3/12">{copy.intro}</TableCell>
              <TableCell className="w-1/12">{copy.status}</TableCell>
              <TableCell className="w-1/12">{copy.finished_script_num}/{copy.script_num}</TableCell>
              <TableCell className="w-2/12">{moment(copy.cjsj).format('YYYY-MM-DD HH:mm')}</TableCell>
              <TableCell className="w-2/12 space-x-2">
                <Button 
                  size="sm" 
                  variant="outline"
                  onClick={() => {
                    setCurrentCopy(copy)
                    setIsEditing(true)
                    setDialogOpen(true)
                  }}
                >
                  编辑
                </Button>
                <Button 
                  size="sm" 
                  variant="ghost"
                  onClick={() => handleDeleteCopy(copy.id)}
                >
                  删除
                </Button>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  )
}
